跳到主要内容

Vue 2:Vue.extend

Vue.extend(options) 基于 Vue 构造器创建组件子类,返回构造器,不会立即创建或挂载实例。Vue 3 使用 createApp() 或渲染 API,不再提供此全局 API。

基本用法​

import Vue from 'vue';

const Profile = Vue.extend({
template: '<p>{{ name }}</p>',
data: () => ({ name: 'Alice' })
});
const instance = new Profile().$mount('#mount-point');

组件的 data 使用函数,保证不同实例有独立状态。不传挂载目标时,$mount() 会生成 DOM,可再插入指定位置。

程序化 Message / Toast​

保留一个创建、挂载与销毁流程,消息类型、文本和时长通过参数传入。

<!-- Message.vue -->
<template>
<div class="message" :class="type">{{ text }}</div>
</template>

<script>
export default {
props: {
text: { type: String, default: '' },
type: { type: String, default: 'info' }
}
};
</script>

<style scoped>
.message {
position: fixed;
top: 40px;
left: 50%;
transform: translateX(-50%);
padding: 12px 20px;
background: #fff;
box-shadow: 0 2px 12px #0003;
z-index: 1000;
}
.success { color: green; }
.warning { color: #b77900; }
.error { color: red; }
</style>
// message.js
import Vue from 'vue';
import Message from './Message.vue';

const MessageConstructor = Vue.extend(Message);

export function showMessage({ text, type = 'info', duration = 3000 }, callback) {
const instance = new MessageConstructor({ propsData: { text, type } });
instance.$mount();
document.body.appendChild(instance.$el);
let closed = false;
const timer = setTimeout(close, duration);

function close() {
if (closed) return;
closed = true;
clearTimeout(timer);
instance.$destroy();
instance.$el.remove();
if (typeof callback === 'function') callback();
}
return close;
}
const close = showMessage({ text: '保存成功', type: 'success', duration: 2000 });
// 也可以提前调用 close()。

只移除 DOM 不会销毁 Vue 实例,必须同时调用 $destroy()。该示例直接在浏览器中调用;若需要离场动画,应在动画结束后再销毁实例。

作为插件使用​

import { showMessage } from './message';

const MessagePlugin = {
install(Vue) {
Vue.prototype.$toast = (text, duration) => showMessage({ text, duration });
Vue.prototype.$vMessage = {};
for (const type of ['info', 'success', 'warning', 'error']) {
Vue.prototype.$vMessage[type] = (options, callback) =>
showMessage({ ...options, type }, callback);
}
}
};
Vue.use(MessagePlugin);

组件中可调用 this.$toast('提示') 或 this.$vMessage.success({ text: '成功' })。插件安装机制见 Vue.use。